<template>
  <aside class="right-sidebar" v-show="showSidebar">
    <div class="right-sidebar-header">
      <div class="header-with-icon">
        <i class="el-icon-connection"></i>
        <span>"{{currentTopic?.title }}"产业链相关文章</span>
      </div>
    </div>

    <div class="right-sidebar-content">
      <!-- 当前对话主题 -->
      <div
        class="current-topic fade-slide-in"
        v-if="showTopic"
        style="animation-delay: 0ms"
      >
        <div class="topic-header">
          <i :class="getTopicIcon(currentTopic.type)"></i>
          <span>{{ currentTopic?.title }}</span>
        </div>
        <div class="topic-stats">
          <div class="stat-item">
            <i class="el-icon-document"></i>
            <span>已累计检索{{ totalArticleCount }}篇相关文章</span>
          </div>
          <div class="stat-item">
            <!-- <i class="el-icon-data-line"></i> -->
            <!-- <span>{{ currentTopic.analysisCount }}个分析报告</span> -->
          </div>
        </div>
      </div>

      <!-- 相关文章列表 -->
      <div
        class="section-title fade-slide-in"
        v-if="showArticleTitle" style="animation-delay: 300ms"
      >
        <i class="el-icon-document"></i>
        <span>{{ nodeTitle }}节点相关文章</span>
      </div>
      <div class="article-list">
        <div
          v-for="(article, index) in displayedArticles"
          :key="index"
          class="article-card fade-slide-in"
          :class="{'type3-card': currentTopic?.type === 'type3'}"
          :style="{ animationDelay: `${600 + index * 200}ms` }"
        >
          <div class="article-header">
            <!-- <span class="article-tag" :class="article.type">{{ article.type }}</span> -->
            <span class="article-date">{{ article.date }}</span>
          </div>
          <h3 class="article-title">{{ article.title }}</h3>
          <p class="article-summary">{{ article.summary }}</p>
          <div class="article-footer">
            <span class="article-source">
              <i class="el-icon-office-building"></i>
              {{ article.source }}
            </span>
            <a :href="article.url" target="_blank" class="read-more">
              阅读全文 <i class="el-icon-right"></i>
            </a>
          </div>
        </div>
      </div>
    </div>
  </aside>
</template>

<script>
export default {
  name: "RightSidebar",
  data() {
    return {
      showSidebar: false,
      showTopic: false,
      showArticleTitle: false,
      showDataTitle: false,
      showCompanyTitle: false,
      currentTopic: null,
      displayedArticles: [],
      displayedData: [],
      displayedCompanies: [],
      realTimeData: [],
      relatedCompanies: [],
      timeoutIds: [],
      totalArticleCount: 0,
      nodeTitle:''
    };
  },
  methods: {
    resetTotalCount() {
      this.totalArticleCount = 0;
      if (this.currentTopic) {
        this.currentTopic.articleCount = 0;
      }
    },
    getTopicIcon(type) {
      const icons = {
        industry: "el-icon-office-building",
        technology: "el-icon-cpu",
        market: "el-icon-data-analysis",
      };
      return icons[type] || "el-icon-document";
    },
    getTrendIcon(trend) {
      return trend === "up" ? "el-icon-top" : "el-icon-bottom";
    },
    clearAllTimeouts() {
      this.timeoutIds.forEach((id) => clearTimeout(id));
      this.timeoutIds = [];
    },
    updateContent(data) {
      console.log("接收到新的侧边栏数据", data);
      // console.log("接收到的 nodeTitle:", data.topic?.nodeTitle);

      // 验证数据
      if (!data || typeof data !== "object") {
        // console.warn("收到无效数据，跳过更新");
        return;
      }

      // 直接使用传递过来的 totalArticleCount
      this.totalArticleCount = data.topic?.totalArticleCount || 0;
      this.nodeTitle= data.topic?.extractedNodeTitle || "";
      // 先停止所有进行中的动画和计时器
      this.clearAllTimeouts();

      // 彻底重置所有状态变量
      this.showSidebar = false; // 先隐藏整个侧边栏，稍后再显示
      this.showTopic = false;
      this.showArticleTitle = false;
      this.showDataTitle = false;
      this.showCompanyTitle = false;

      // 完全清空所有数据数组 - 直接重新赋值而不是清空
      this.displayedArticles = [];
      this.displayedData = [];
      this.displayedCompanies = [];
      this.realTimeData = [];
      this.relatedCompanies = [];

      // 等待DOM更新，确保所有内容完全清除
      this.$nextTick(() => {
        // 设置主题数据 - 创建全新对象而不是修改现有对象
        this.currentTopic = {
          title: data.topic ? data.topic.title : "产业链分析",
          nodeTitle: this.extractedNodeTitle || "",
          type: data.topic ? data.topic.type : "industry",
          articleCount: this.totalArticleCount,
          analysisCount: 0,
        };

        // console.log("设置后的 currentTopic:", this.currentTopic);

        // 重新加载数据，确保是全新的数组
        this.realTimeData = Array.isArray(data.marketData)
          ? [...data.marketData]
          : [];
        this.relatedCompanies = Array.isArray(data.companies)
          ? [...data.companies]
          : [];

        // 处理文章数据
        const articles = Array.isArray(data.articles) ? data.articles : [];
        // console.log(`准备处理${articles.length}篇文章`);

        // 确保文章数据有效性并去重
        const uniqueArticles = this.removeDuplicateArticles(articles);
        // console.log(`去重后剩余${uniqueArticles.length}篇文章`);

        // 重新显示侧边栏
        this.showSidebar = true;

        // 重新启动动画序列
        // 1. 显示主题区域
        const id1 = setTimeout(() => {
          // console.log("显示主题区域:", this.currentTopic.title);
          this.showTopic = true;
        }, 100);
        this.timeoutIds.push(id1);
 
        
        // 2. 处理文章区域
        if (uniqueArticles.length > 0) {
          
          const id2 = setTimeout(() => {
            // console.log('显示文章标题区域');
            this.showArticleTitle = true;
          }, 300);
          this.timeoutIds.push(id2);

          // 逐篇添加文章，带延迟
          uniqueArticles.forEach((article, index) => {
            const id = setTimeout(() => {
              // console.log(
              //   `添加文章 ${index + 1}/${uniqueArticles.length}: ${
              //     article.title
              //   }`
              // );
              this.displayedArticles.push({ ...article }); // 使用对象展开创建新对象
            }, 600 + index * 200);
            this.timeoutIds.push(id);
          });
        } else {
          // console.log("没有文章数据，跳过文章区域显示");
        }

        // 3. 处理数据区域
        if (this.realTimeData.length > 0) {
          const id3 = setTimeout(() => {
            this.showDataTitle = true;
          }, 1200);
          this.timeoutIds.push(id3);

          this.realTimeData.forEach((data, index) => {
            const id = setTimeout(() => {
              this.displayedData.push({ ...data });
            }, 1500 + index * 200);
            this.timeoutIds.push(id);
          });
        }

        // 4. 处理企业区域
        if (this.relatedCompanies.length > 0) {
          const id4 = setTimeout(() => {
            this.showCompanyTitle = true;
          }, 2000);
          this.timeoutIds.push(id4);

          this.relatedCompanies.forEach((company, index) => {
            const id = setTimeout(() => {
              this.displayedCompanies.push({ ...company });
            }, 2300 + index * 200);
            this.timeoutIds.push(id);
          });
        }
      });
    },
    removeDuplicateArticles(articles) {
      const uniqueArticles = [];
      const urlSet = new Set();
      const titleSet = new Set();

      articles.forEach((article) => {
        if (!article || !article.title || !article.url) {
          // console.warn("跳过无效文章数据:", article);
          return;
        }

        if (urlSet.has(article.url) || titleSet.has(article.title)) {
          // console.log(`跳过重复文章: ${article.title}`);
          return;
        }

        urlSet.add(article.url);
        titleSet.add(article.title);
        uniqueArticles.push(article);
      });

      // console.log(`文章去重后数量: ${uniqueArticles.length}`);
      return uniqueArticles;
    },
  },
  created() {
    this.$root.$on("update-sidebar", this.updateContent);
    this.$root.$on("message-processing", this.resetTotalCount);
    console.log("RightSidebar created and listening for updates");
  },
  beforeDestroy() {
    this.$root.$off("update-sidebar", this.updateContent);
    this.$root.$off("message-processing", this.resetTotalCount);
  },
};
</script>

<style scoped>
.right-sidebar {
  width: 320px;
  height: 100vh;
  background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
  border-left: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  animation: slideIn 0.3s ease;
  display: flex;
  flex-direction: column;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.right-sidebar-header {
  height: 60px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e8f2ff;
  background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
}

.header-with-icon {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.header-with-icon i {
  font-size: 20px;
  color: #1a73e8;
}

.right-sidebar-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.current-topic {
  background: linear-gradient(135deg, #f0f7ff 0%, #ffffff 100%);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.topic-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.topic-header i {
  font-size: 24px;
  color: #1a73e8;
}

.topic-header span {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.topic-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 14px;
}

.stat-item i {
  color: #1a73e8;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e8f2ff;
}

.section-title i {
  font-size: 18px;
  color: #1a73e8;
}

.section-title span {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.article-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}

.article-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  will-change: transform, opacity;
}

.article-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.article-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.article-tag.深度分析 {
  background: #e6f7ff;
  color: #1a73e8;
}

.article-tag.行业报告 {
  background: #f6ffed;
  color: #52c41a;
}

.article-date {
  font-size: 12px;
  color: #999;
}

.article-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.article-summary {
  font-size: 13px;
  color: #666;
  margin-bottom: 12px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.article-source {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.read-more {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #1a73e8;
  text-decoration: none;
}

.read-more:hover {
  text-decoration: underline;
}

.data-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 24px;
}

.data-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.data-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #f0f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.data-icon i {
  font-size: 24px;
  color: #1a73e8;
}

.data-info {
  flex: 1;
}

.data-title {
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
}

.data-value {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.data-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.data-trend.up {
  color: #52c41a;
}

.data-trend.down {
  color: #ff4d4f;
}

.company-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.company-card {
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  display: flex;
  align-items: center;
  gap: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.company-logo {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  object-fit: cover;
}

.company-info {
  flex: 1;
}

.company-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.company-type {
  font-size: 12px;
  color: #666;
}

.company-market-info {
  text-align: right;
}

.stock-code {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.stock-price {
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: flex-end;
}

.stock-price.up {
  color: #52c41a;
}

.stock-price.down {
  color: #ff4d4f;
}

@keyframes fadeSlideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-slide-in {
  animation: fadeSlideIn 0.5s ease forwards;
  opacity: 0;
}

.type3-card {
  background: #f0f7ff !important;
  border: 1px solid #bae7ff;
}

.type3-card .article-title {
  color: #1890ff;
}

.type3-card .article-summary {
  color: #4b5563;
}

.type3-card:hover {
  background: #e6f7ff !important;
  border-color: #69c0ff;
}
</style> 